package edu.washington.vaccine.ui;

import java.util.Calendar;
import java.util.Date;

import android.widget.DatePicker;


public class DateLimiter implements DatePicker.OnDateChangedListener {
	Date date = new Date();
	Date current;
	boolean reset = false;

	static DateLimiter inst = null;

	protected DateLimiter() {

	}

	public static DateLimiter getInstance() {
		if (inst == null)
			inst = new DateLimiter();

		return inst;
	}

	public void onDateChanged(DatePicker dp, int year, int month, int day) {
		Calendar c = Calendar.getInstance();
		current = c.getTime();
		date.setDate(day);
		date.setMonth(month);
		date.setYear(year - 1900);
		
		if (date.after(current)) {
			reset = true;
		}

//		System.out.println(date);
//		System.out.println(c.getTime());
//		System.out.println("is the date later than today? " + date.after(c.getTime()));

		
		if (reset) {
			reset = false;
			
			date.setDate(date.getDate() - 1);
			if (date.after(current))
				date.setDate(date.getDate() + 1);
			else {
				dp.updateDate(date.getYear() + 1900, date.getMonth(), date.getDate());
				return;
			}
			
			date.setMonth(date.getMonth() - 1);
			if (date.after(current))
				date.setMonth(date.getMonth() + 1);
			else {
				dp.updateDate(date.getYear() + 1900, date.getMonth(), date.getDate());
				return;
			}
			
			date.setYear(date.getYear() - 1);
			if (date.after(current))
				date.setYear(date.getYear() + 1);
			else {
				dp.updateDate(date.getYear() + 1900, date.getMonth(), date.getDate());
				return;
			}
		}
	}
}
